﻿using CommonAdmin.Dto;
using CommonAdmin.Web.Models;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace CommonAdmin.Web.Controllers.Api
{
	[ApiController]
	[Route("api/[controller]")]
	public class DictionaryController : ControllerBase
	{
		private readonly ILogger<DictionaryController> _logger;
		private readonly ISqlSugarClient _db;
		public DictionaryController(ILogger<DictionaryController> logger, ISqlSugarClient db)
		{
			_logger = logger;
			_db = db;
		}
		[HttpGet("list")]
		public JsonResult GetList()
		{
			ResultViewModel result = new ResultViewModel();
			return new JsonResult(result);
		}
		[HttpPost("add")]
		public JsonResult AddFirst(string name)
		{
			ResultViewModel result = new ResultViewModel();
			try
			{
				result.code = (int)CodeEnum.请求失败;

				if (string.IsNullOrWhiteSpace(name))
				{
					result.msg = "字典名称不能为空";
					return new JsonResult(result);
				}

				var query = _db.Queryable<DictionaryDto>().Where(o => o.ParentId == "-1").OrderBy(o => o.Id).ToList();
				string id = "01";
				if (query.Count > 0)
				{
					id = (int.Parse(query[query.Count - 1].Id) + 1).ToString().PadLeft(2, '0');
				}
				var model = new DictionaryDto()
				{
					Id = id,
					Name = name,
					ParentId = "-1"
				};
				_db.Insertable<DictionaryDto>(model).ExecuteCommand();
				result.code = (int)CodeEnum.请求成功;
			}
			catch (Exception ex)
			{
				result.code = (int)CodeEnum.内部错误;
				result.msg = CodeEnum.内部错误.ToString();
				_logger.LogError(ex, "添加字典失败");
			}
			return new JsonResult(result);
		}
		[HttpPost("addchild")]
		public JsonResult AddSecond(string parentId, string name)
		{
			ResultViewModel result = new ResultViewModel();
			try
			{
				result.code = (int)CodeEnum.请求失败;

				if (string.IsNullOrWhiteSpace(name))
				{
					result.msg = "字典名称不能为空";
					return new JsonResult(result);
				}

				var query = _db.Queryable<DictionaryDto>().Where(o => o.ParentId == parentId).OrderBy(o => o.Id).ToList();
				string id = $"{parentId}001";
				if (query.Count > 0)
				{
					id = (int.Parse(query[query.Count - 1].Id) + 1).ToString().PadLeft(3, '0');
				}
				var model = new DictionaryDto()
				{
					Id = id,
					Name = name,
					ParentId = parentId
				};
				_db.Insertable<DictionaryDto>(model).ExecuteCommand();
				result.code = (int)CodeEnum.请求成功;
			}
			catch (Exception ex)
			{
				result.code = (int)CodeEnum.内部错误;
				result.msg = CodeEnum.内部错误.ToString();
				_logger.LogError(ex, "添加字典失败");
			}
			return new JsonResult(result);
		}
	}
}
